#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Ali Bao Bao 电商系统快速启动脚本
集成了商品搜索、推荐系统、购物车和物流功能
"""

import sys
import os

# 添加models目录到路径
current_dir = os.path.dirname(os.path.abspath(__file__))
# 获取ali_bao_bao目录（启动盘的父目录）
ali_bao_bao_dir = os.path.join(current_dir, "..", "ali_bao_bao")
ali_bao_bao_dir = os.path.abspath(ali_bao_bao_dir)
models_dir = os.path.join(ali_bao_bao_dir, "models")

# 添加ali_bao_bao目录到路径
if ali_bao_bao_dir not in sys.path:
    sys.path.insert(0, ali_bao_bao_dir)
if models_dir not in sys.path:
    sys.path.insert(0, models_dir)

def check_dependencies():
    """检查依赖包是否已安装"""
    print("正在检查系统依赖...")
    
    required_packages = {
        'requests': '网络请求库（用于百度地图API）',
        'json': 'JSON数据处理（Python内置）',
        'datetime': '日期时间处理（Python内置）'
    }

    missing_packages = []
    
    for package, description in required_packages.items():
        try:
            __import__(package)
            print(f"  ✓ {package} - {description}")
        except ImportError:
            print(f"  ✗ {package} - {description} [缺失]")
            missing_packages.append(package)
    
    if missing_packages:
        print(f"\n❌ 缺少以下依赖包：{', '.join(missing_packages)}")
        print("请运行以下命令安装：")
        print(f"  pip install {' '.join(missing_packages)}")
        return False
    
    print("\n✓ 所有依赖包检查通过！\n")
    return True


def check_files():
    """检查必要文件是否存在"""
    print("正在检查系统文件...")
    
    # 获取ali_bao_bao目录
    ali_bao_bao_dir = os.path.join(current_dir, "..", "ali_bao_bao")
    ali_bao_bao_dir = os.path.abspath(ali_bao_bao_dir)
    
    required_files = {
        "models/integrated_system.py": "主系统文件",
        "models/cart.py": "购物车模块",
        "models/product.py": "商品模块",
        "models/user.py": "用户模块",
        "new_models/物流.py": "物流模块",
        "new_models/地图坐标获取/code/calculate.py": "地理计算模块",
        "new_models/地图坐标获取/code/akget.py": "API密钥管理",
        "data/商品数据集.xlsx": "商品数据（或 .json）"
    }
    
    missing_files = []
    
    for file_path, description in required_files.items():
        full_path = os.path.join(ali_bao_bao_dir, file_path)
        # 对于商品数据集，检查xlsx或json任一存在即可
        if "商品数据集" in file_path:
            xlsx_path = full_path
            json_path = full_path.replace('.xlsx', '.json')
            if os.path.exists(xlsx_path) or os.path.exists(json_path):
                print(f"  ✓ {file_path} - {description}")
                continue
        
        if os.path.exists(full_path):
            print(f"  ✓ {file_path} - {description}")
        else:
            print(f"  ✗ {file_path} - {description} [缺失]")
            missing_files.append(file_path)
    
    if missing_files:
        print(f"\n❌ 缺少以下文件：")
        for file in missing_files:
            print(f"  - {file}")
        return False
    
    print("\n✓ 所有系统文件检查通过！\n")
    return True


def main():
    """主函数"""
    print("="*60)
    print("Ali Bao Bao 电商系统")
    print("="*60)
    print()
    
    # 检查依赖
    if not check_dependencies():
        print("\n系统启动失败：缺少必要的依赖包")
        input("\n按回车键退出...")
        return
    
    # 检查文件
    if not check_files():
        print("\n系统启动失败：缺少必要的系统文件")
        input("\n按回车键退出...")
        return
    
    # 启动主系统
    print("="*60)
    print("系统检查完成，正在启动...")
    print("="*60)
    print()
    
    try:
        # 导入并运行主系统
        from integrated_system import main as system_main
        system_main()
    except ImportError as e:
        print(f"\n❌ 导入错误：{str(e)}")
        print("\n可能的原因：")
        print("  1. 文件路径不正确")
        print("  2. 模块之间的依赖关系有问题")
        print("  3. Python版本不兼容（建议使用Python 3.7+）")
        print("\n请检查错误信息并修复后重试")
        input("\n按回车键退出...")
    except Exception as e:
        print(f"\n❌ 系统运行错误：{str(e)}")
        print("\n请查看错误信息并联系技术支持")
        import traceback
        traceback.print_exc()
        input("\n按回车键退出...")


if __name__ == "__main__":
    try:
        main()
    except KeyboardInterrupt:
        print("\n\n用户中断，系统退出")
    except Exception as e:
        print(f"\n\n未预期的错误：{str(e)}")
        import traceback
        traceback.print_exc()
        input("\n按回车键退出...")

